#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QSerialPortInfo>
#include <QStandardItemModel>
#include <QList>
#include <QMetaEnum>
#include <QScrollBar>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    ,ui(new Ui::MainWindow)
    ,_msp(nullptr)

{
    ui->setupUi(this);
    init();
}

MainWindow::~MainWindow()
{
    delete ui;
    if(_file.isOpen()) _file.close();
}

void MainWindow::init()
{
    init_cmb_sp();
    OptionSet::initComboBox(ui->cmb_baudrate,OptionSet::SP_BaudRate);
    OptionSet::initComboBox(ui->cmb_databits,OptionSet::SP_DataBits);
    OptionSet::initComboBox(ui->cmb_parity,OptionSet::SP_Parity);
    OptionSet::initComboBox(ui->cmb_stopbits,OptionSet::SP_StopBits);
    setSPContolStatus(true);
    ui->pe_history->setMaximumBlockCount(1000);
    ui->chk_hexreceive->setChecked(true);
    _file.setFileName("myrs485log.txt");
    _file.open(QIODevice::WriteOnly|QIODevice::Append);
}

void MainWindow::init_cmb_sp()
{
    QStandardItemModel *spModel = new QStandardItemModel(ui->cmb_sp);
    const QList<QSerialPortInfo> spl=QSerialPortInfo::availablePorts();
    for(const QSerialPortInfo &info:spl)
    {
        QStandardItem *item = new QStandardItem(info.portName());
         item->setToolTip(info.portName() + " " + info.description());
         spModel->appendRow(item);
    }

     ui->cmb_sp->clear();
     ui->cmb_sp->setModel(spModel);

}


int MainWindow::getSPSetting(MySerialPortSettings &setting)
{
    QString portName=ui->cmb_sp->currentText();
    if(portName.isEmpty()) return -1;
    if(ui->cmb_baudrate->currentIndex()<0) return -2;
    if(ui->cmb_databits->currentIndex()<0) return -3;
    if(ui->cmb_parity->currentIndex()<0) return -4;
    if(ui->cmb_stopbits->currentIndex()<0) return -5;

    setting.portName=portName;
    setting.baudRate=QSerialPort::BaudRate(ui->cmb_baudrate->currentData().toInt());
    setting.dataBits=QSerialPort::DataBits(ui->cmb_databits->currentData().toInt());
    setting.parity=QSerialPort::Parity(ui->cmb_parity->currentData().toInt());
    setting.stopBits=QSerialPort::StopBits(ui->cmb_stopbits->currentData().toInt());

    return 0;
}



void MainWindow::setSPContolStatus(bool v)
{
    ui->cmb_sp->setEnabled(v);
    ui->cmb_baudrate->setEnabled(v);
    ui->cmb_databits->setEnabled(v);
    ui->cmb_parity->setEnabled(v);
    ui->cmb_stopbits->setEnabled(v);
    ui->chk_hexreceive->setEnabled(v);
    QString radioStyleSheet=QString("QPushButton{"
                                   "color:black;"
                                   "background-color:transparent;"
                                   "border:1px solid gray;"
                                   "}"
                                   "");
    QString text;
    QString iconPath;

    if(v)
    {
        iconPath=":/pics/start.png";
        text=tr("open");
    }
    else
    {
        iconPath=":/pics/stop.png";
        text=tr("close");
    }
    ui->btn_oc->setStyleSheet(radioStyleSheet);
    ui->btn_oc->setIconSize(QSize(32,32));
    ui->btn_oc->setIcon(QIcon(iconPath));
    ui->btn_oc->setText(text);

}


//bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, long* result)
//{
//    Q_UNUSED(eventType)
//    Q_UNUSED(result)

//    MSG* msg = reinterpret_cast<MSG*>(message);
//    if (msg->message == WM_DEVICECHANGE)//发生硬件热插拔事件，更新可用串口号
//    {
//        init_cmb_sp();
//    }
//    return false;
//}



void MainWindow::on_btn_oc_clicked()
{
    //打开-->关闭
    if(_msp)
    {
        _msp->deleteLater();
        _msp=nullptr;
        setSPContolStatus(true);

        ui->pe_history->appendPlainText(tr("port has closed !"));

    }
    //关闭-->打开
    else{
        //得到串口参数
        MySerialPortSettings setting;
        int rt=getSPSetting(setting);
        if(rt<0)
        {
            ui->pe_history->appendPlainText(tr("parameter error!"));
            return;
        }
        //新建串口
        RES res;
        _msp=new MySerialPort(setting,res);
        if(res.returnCode<0)
        {
                _msp->deleteLater();
                _msp=nullptr;
                ui->pe_history->appendPlainText(tr("failed to create SerialPort:")+res.msg);
                return;
        }
        else
        {

             setSPContolStatus(false);
             ui->pe_history->appendPlainText(tr("open port!"));
             connect(_msp,&MySerialPort::sgSPReceiveData,this,&MainWindow::slSPReceiveData,Qt::QueuedConnection);
             connect(this,&MainWindow::sgSendData,_msp,&MySerialPort::slSendData,Qt::QueuedConnection);
        }


    }


}

void MainWindow::slSPReceiveData(const QByteArray data)
{

    //ui->pe_history->moveCursor (QTextCursor::Start);
    ui->pe_history->moveCursor (QTextCursor::End);

    //ui->pe_history->insertPlainText(data.toHex());
//    if(ui->pe_history->blockCount()>2000)
//    {

//    }
    if(_isHex)
    {
        //ui->pe_history->appendPlainText(data.toHex());
        ui->pe_history->insertPlainText(data.toHex());
        //qDebug()<<data.toHex();
        _file.write(data.toHex());
    }
    else
    {
         //ui->pe_history->appendPlainText(data);
         ui->pe_history->insertPlainText(data);
         //qDebug()<<data;
         _file.write(data);
    }
    //移动滚动条到底部
    QScrollBar *scrollbar = ui->pe_history->verticalScrollBar();
    if (scrollbar)
    {
        scrollbar->setSliderPosition(scrollbar->maximum());
    }

}


void MainWindow::on_btn_send_clicked()
{
    QByteArray bytes=ui->pe_send->toPlainText().toLatin1();
    emit sgSendData(bytes);
}




void MainWindow::on_chk_hexreceive_clicked(bool checked)
{
    _isHex=checked;
}

